package com.cpo.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.digester.annotations.CreationRule;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cpo.domain.CreditCard;
import com.cpo.domain.Person;
import com.cpo.interfaces.ICreditCardDao;

@Repository
@Transactional
public class CreditCardDao implements ICreditCardDao {

	protected static Logger logger = Logger.getLogger("service");
	
	@Autowired
	private SessionFactory sessionFactory;
	
	
	
	public void add(Integer personId, CreditCard creditCard) {
		logger.debug("Adding a new credit card");
		Session session = sessionFactory.getCurrentSession();
		session.save(creditCard);
		
		Person existingPerson = (Person) session.get(Person.class, personId);
		existingPerson.getCreditCards().add(creditCard);
		session.save(existingPerson);
	}

	
	public void delete(Integer id) {
		logger.debug("Deleting existing credit cards");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("DELETE FROM PERSON_CREDIT_CARD"+"WHERE creditCards_ID="+id);
		query.executeUpdate();
	}

	
	public void edit(CreditCard creditCard) {
		logger.debug("Editing existing creditCard");
		Session session = sessionFactory.getCurrentSession();
		CreditCard existingCreditCard = (CreditCard) session.get(CreditCard.class,creditCard.getId());
		
		existingCreditCard.setNumber(creditCard.getNumber());
		existingCreditCard.setType(creditCard.getType());
		session.save(existingCreditCard);
		
		
	}

	
	public CreditCard get(Integer id) {
		Session session = sessionFactory.getCurrentSession();
		CreditCard creditCard = (CreditCard) session.get(CreditCard.class, id);
		return creditCard;
	}

	
	public List<CreditCard> getAll(Integer personId) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person as p LEFT JOIN FETCH p.creditCards WHERE p.id="+personId);
		Person person = (Person) query.uniqueResult();
		return new ArrayList<CreditCard>(person.getCreditCards());
	}

	
	public List<CreditCard> getAll() {
	
		logger.debug("Retriving all credit cards");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM CreditCard");
		return query.list();

	}

	
}
